package hello;

import java.util.Arrays;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.elasticsearch.client.Client;
import org.elasticsearch.common.geo.GeoPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.client.NodeClientFactoryBean;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

@SpringBootApplication
@EnableElasticsearchRepositories
public class Application {
	@Autowired ElasticsearchOperations operations;
	@Autowired ConferenceRepository repository;

	@Bean
	public NodeClientFactoryBean client() {

		NodeClientFactoryBean bean = new NodeClientFactoryBean(true);
		bean.setClusterName(UUID.randomUUID().toString());
		bean.setEnableHttp(false);
		bean.setPathData("target/elasticsearchTestData");
		bean.setPathHome("src/test/resources/test-home-dir");

		return bean;
	}

	@Bean
	public ElasticsearchTemplate elasticsearchTemplate(Client client) throws Exception {
		return new ElasticsearchTemplate(client);
	}

	@PreDestroy
	public void deleteIndex() {
		operations.deleteIndex(Conference.class);
	}

	@PostConstruct
	public void insertDataSample() {

		// Remove all documents
		repository.deleteAll();
		operations.refresh(Conference.class);

		// Save data sample
		Conference cf1= new Conference();
		cf1.setDate("2014-11-06");
		cf1.setName("Spring eXchange 2014 - London");
		repository.save(cf1);
				//.keywords(Arrays.asList("java", "spring")).location(new GeoPoint(51.500152D, -0.126236D)).build());
		Conference cf2= new Conference();
		cf2.setDate("2014-12-07");
		cf2.setName("Scala eXchange 2014 - London");
		repository.save(cf2);
				//.keywords(Arrays.asList("scala", "play", "java")).location(new GeoPoint(51.500152D, -0.126236D)).build());
		Conference cf3= new Conference();
		cf3.setDate("2014-11-20");
		cf3.setName("Elasticsearch 2014 - Berlin");
		repository.save(cf3);
				//.keywords(Arrays.asList("java", "elasticsearch", "kibana")).location(new GeoPoint(52.5234051D, 13.4113999))
				//.build());
		Conference cf4= new Conference();
		cf4.setDate("2014-11-12");
		cf4.setName("AWS London 2014");
		repository.save(cf4);
	}

}
